<template>
	<el-dialog :title="dialogTitle" :visible.sync="visible" append-to-body width="560px">
		<el-form ref="form" size="medium" :model="enumFrom" :rules="enumRules" label-width="90px" class="enum_form_wrapper">
			<el-form-item label="枚举名称" prop="deName">
				<el-input v-model="enumFrom.deName"></el-input>
			</el-form-item>
			<el-row>
				<el-col :span="15">
					<el-form-item label="枚举值" prop="deValue">
						<el-input v-model="enumFrom.deValue"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="9">
					<el-form-item label="排序" prop="sort" label-width="60px">
						<el-input-number v-model="enumFrom.sort" controls-position="right" :min="1" :max="999"></el-input-number>
					</el-form-item>
				</el-col>
			</el-row>
			<el-form-item label="枚举描述">
				<el-input type="textarea" v-model="enumFrom.content"></el-input>
			</el-form-item>
		</el-form>
		<template slot="footer">
			<el-button size="medium" @click="visible = false">取消</el-button>
			<el-button size="medium" type="primary" :loading="btnLoading" @click="handleSubmitForm">{{ addOrEdit ? '新增' : '修改' }}</el-button>
		</template>
	</el-dialog>
</template>

<script>
import { addedDictDetail, updateDictDetail } from '@/api/system/tbSysDictDetail';
export default {
	props: {
		value: {
			type: Boolean,
			default: false
		},
		dictId: String,
		enumData: {
			type: Object,
			default() {
				return {};
			}
		}
	},
	data() {
		return {
			visible: this.value,
			enumFrom: {},
			enumRules: {
				deName: [{ required: true, message: '请输入枚举名称', trigger: 'blur' }],
				deValue: [{ required: true, message: '请输入枚举值', trigger: 'blur' }]
			},
			btnLoading: false
		};
	},
	computed: {
		addOrEdit() {
			return Object.keys(this.enumData).length === 0;
		},
		dialogTitle() {
			return `${this.addOrEdit ? '新增' : '修改'}字典枚举`;
		}
	},
	watch: {
		value(flag) {
			this.visible = flag;
		},
		visible(flag) {
			this.$emit('input', flag);
			if (!flag) return false;
			this.$nextTick(() => {
				this.$refs['form'].resetFields();
				this.enumFrom = this.addOrEdit ? { sort: 1 } : { ...this.enumData };
			});
		}
	},
	methods: {
		handleSubmitForm() {
			this.$refs['form'].validate(async (valid) => {
				if (!valid) return false;
				this.btnLoading = true;
				await this.submitFormRequest();
				this.btnLoading = false;
			});
		},

		//添加/修改枚举请求
		async submitFormRequest() {
			let params = { ...this.enumFrom, dictId: this.dictId };
			let requestFun = eval(this.addOrEdit ? addedDictDetail : updateDictDetail);
			let result = await requestFun(params).then((res) => res.data);
			if (result.code === '0') {
				this.$emit('refresh');
				this.visible = false;
				this.$store.dispatch('getOpenDictData');
				this.$showCustomMessage('success', `${this.addOrEdit ? '新增' : '修改'}枚举成功`);
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.enum_form_wrapper::v-deep {
	width: 100%;
	padding: 10px 6px 0 0;
	box-sizing: border-box;
	.el-input-number {
		width: 100%;
	}
}
</style>
